import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../../../bean/bean_train.dart';
import '../../../bean/bean_video_course.dart';
import '../../../utils/date_utils.dart';

class CourseSignController extends GetxController {
  final BeanVideoCourse beanVideoCourse;
  final int trainId;

  CourseSignController(this.beanVideoCourse, this.trainId);

  bool _isLoading = true;

  bool get isLoading => _isLoading;

  ///是否可以签到
  AppCourseLineSignResponseEntity signResponseEntity;

  AppCourseLineSignStatEntity signStatEntity;

  ///当日的签到记录
  SignRecoderBean signRecoderBean;
  bool _submitSignLoading = false;

  bool get submitSignLoading => _submitSignLoading;

  Future<bool> initRequest() async {
    await getSignRequest();
    //获取是否可以签到
    Map<String, dynamic> map = Map();
    map["courseId"] = beanVideoCourse.id;
    map["trainId"] = trainId;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.getTrainSignOpenUrl,
      jsonMap: map,
      encrypt: true,
    );

    if (responseInfo.success) {
      if (responseInfo.data != null) {
        signResponseEntity =
            AppCourseLineSignResponseEntity.fromMap(responseInfo.data);
      }
    }
    if (signResponseEntity == null) {
      signResponseEntity = AppCourseLineSignResponseEntity(false, "暂不可签到");
      _isLoading = false;
      update(["root"]);
      return true;
    }
    if (!signResponseEntity.isOpen) {
      _isLoading = false;
      update(["root"]);
      return true;
    }

    //获取当日的签到记录

    ResponseInfo daySignResponse = await DioUtils.instance.postRequest(
      url: HttpHelper.getRecoderFromDayUrl,
      jsonMap: map,
      encrypt: true,
    );
    if (daySignResponse.success) {
      if (daySignResponse.data != null) {
        signRecoderBean = SignRecoderBean.fromMap(daySignResponse.data);
        update(["time-day"]);
      }
    }
    startTimer();
    _isLoading = false;
    update(["root"]);
  }

  Future<bool> getSignRequest() async {
    Map<String, dynamic> map = Map();
    map["courseId"] = beanVideoCourse.id;
    map["trainId"] = trainId;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.getTrainSignStatyUrl,
      jsonMap: map,
      encrypt: true,
    );

    if (responseInfo.success) {
      if (responseInfo.data != null) {
        signStatEntity = AppCourseLineSignStatEntity.fromMap(responseInfo.data);
      }
    }
    update(["sign-stat"]);
    return true;
  }

  Timer _timer;
  String currentTimeStr = "";

  @override
  void onReady() {
    super.onReady();
  }

  stopTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  startTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
    if (signRecoderBean != null) {
      if (signRecoderBean.signUpTime != null &&
          !signRecoderBean.signUpTime.isEmpty &&
          signRecoderBean.signToTime != null &&
          !signRecoderBean.signUpTime.isEmpty) {
        return;
      }
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      currentTimeStr = ViDateUtils.getNowDateStr(format: "HH:mm:ss");
      update(["time"]);
    });
  }

  @override
  void onClose() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
    super.onClose();
  }

  void signOnClick() async {
    _submitSignLoading = true;
    update(["time"]);
    //获取是否可以签到
    Map<String, dynamic> map = Map();
    map["courseId"] = beanVideoCourse.id;
    map["trainId"] = trainId;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.saveOnLineSignUrl,
      jsonMap: map,
      encrypt: true,
    );
    _submitSignLoading = false;
    if (responseInfo.success) {
      if (responseInfo.data != null) {
        signRecoderBean = SignRecoderBean.fromMap(responseInfo.data);
      } else {
        Get.defaultDialog(
            title: "签到失败",
            content: Text(responseInfo.message ?? "网络请求错误"),
            textCancel: "关闭");
      }
    } else {
      Get.defaultDialog(
          title: "签到失败",
          content: Text(responseInfo.message ?? "网络请求错误"),
          textCancel: "关闭");
    }
    update(["time-day", "time"]);
  }

  void signOffFunction() async {
    _submitSignLoading = true;
    update(["time"]);
    //签退
    Map<String, dynamic> map = Map();
    map["courseId"] = beanVideoCourse.id;
    map["trainId"] = trainId;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.saveOffLineSignUrl,
      jsonMap: map,
      encrypt: true,
    );
    _submitSignLoading = false;
    if (responseInfo.success) {
      if (responseInfo.data != null) {
        signRecoderBean = SignRecoderBean.fromMap(responseInfo.data);
      } else {
        Get.defaultDialog(
            title: "签到失败", content: Text(responseInfo.message ?? "网络请求错误"));
      }
    } else {
      Get.defaultDialog(
          title: "签到失败", content: Text(responseInfo.message ?? "网络请求错误"));
    }
    update(["time-day", "time"]);
  }

  void updateSignUpFunction({@required String url}) async {
    _submitSignLoading = true;
    update(["time"]);
    //签退
    Map<String, dynamic> map = Map();
    map["courseId"] = beanVideoCourse.id;
    map["trainId"] = trainId;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: url,
      jsonMap: map,
      encrypt: true,
    );
    _submitSignLoading = false;
    if (responseInfo.success) {
      if (responseInfo.data != null) {
        signRecoderBean = SignRecoderBean.fromMap(responseInfo.data);
      } else {
        Get.defaultDialog(
            title: "修改失败", content: Text(responseInfo.message ?? "网络请求错误"));
      }
    } else {
      Get.defaultDialog(
          title: "修改失败", content: Text(responseInfo.message ?? "网络请求错误"));
    }
    update(["time-day", "time"]);
  }

  void signOffClick() async {
    dynamic result = await Get.defaultDialog(
        title: "提示",
        content: Text("确认签退吗?"),
        textCancel: "取消",
        textConfirm: "确认",
        onConfirm: () {
          Get.back(result: true);
        });
    if (result != null && result) {
      signOffFunction();
    }
  }

//点击更新 开始学习时间
  void updateSinOffClick() async {
    if (signRecoderBean == null) {
      return;
    }
    String signToTime = signRecoderBean.signToTime ?? "";
    String signUpTime = signRecoderBean.signUpTime ?? "";
    if (signToTime.isEmpty) {
      return;
    }
    if (signUpTime.isEmpty) {
      return;
    }
    dynamic result = await Get.defaultDialog(
        title: "提示",
        content: Text("确认修改签退时间为当前吗?"),
        textCancel: "取消",
        textConfirm: "确认",
        onConfirm: () {
          Get.back(result: true);
        });
    if (result != null && result) {
      updateSignUpFunction(url: HttpHelper.updateOffLineSignUrl);
    }
  }

  //点击更新 结束学习时间
  void updateSinToClick() async {
    if (signRecoderBean == null) {
      return;
    }
    String signToTime = signRecoderBean.signToTime ?? "";
    String signUpTime = signRecoderBean.signUpTime ?? "";
    if (signToTime.isEmpty) {
      return;
    }
    if (signUpTime.isNotEmpty) {
      ToastUtils.showToast("已签退 不可修改签到时间");
      return;
    }
    dynamic result = await Get.defaultDialog(
        title: "提示",
        content: Text("确认修改签到时间为当前吗?"),
        textCancel: "取消",
        textConfirm: "确认",
        onConfirm: () {
          Get.back(result: true);
        });
    if (result != null && result) {
      updateSignUpFunction(url: HttpHelper.updateOnLineSignUrl);
    }
  }
}
